<template>
  <div class="collect-content">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <div class="stats">
          <el-tag type="info">总计 {{ total }}</el-tag>
          <el-tag type="primary">已收藏 {{ favoriteCount }}</el-tag>
        </div>
        <el-button type="primary" :icon="Plus" @click="handleCreateItem">
          新增收藏
        </el-button>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索收藏内容..."
          :prefix-icon="Search"
          clearable
          style="width: 300px;"
          @input="handleSearch"
        />
        <el-select v-model="selectedType" placeholder="类型" clearable style="width: 120px;">
          <el-option label="全部" value="" />
          <el-option label="文本" value="text" />
          <el-option label="链接" value="link" />
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
        </el-select>
        <el-select v-model="selectedFavoriteStatus" placeholder="状态" clearable style="width: 120px;">
          <el-option label="全部" :value="undefined" />
          <el-option label="已收藏" :value="true" />
          <el-option label="未收藏" :value="false" />
        </el-select>

        <!-- 视图模式切换 -->
        <el-radio-group v-model="viewMode" size="default">
          <el-radio-button value="grid">
            <el-icon><Grid /></el-icon>
            网格
          </el-radio-button>
          <el-radio-button value="waterfall">
            <el-icon><Menu /></el-icon>
            瀑布流
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="favorites-main" v-loading="loading">
      <div v-if="favoriteItems.length === 0" class="empty-state">
        <el-empty description="暂无收藏内容">
          <el-button type="primary" @click="$router.push('/collect/create')">
            添加第一个收藏
          </el-button>
        </el-empty>
      </div>
      <div v-else :class="viewMode === 'waterfall' ? 'favorites-waterfall' : 'favorites-grid'">
        <CollectCard
          v-for="item in favoriteItems"
          :key="item.id"
          :item="item"
          @view="handleViewItem"
          @edit="handleEditItem"
          @delete="handleDeleteItem"
          @toggle-favorite="handleToggleFavorite"
        />
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Grid, Menu } from '@element-plus/icons-vue'
import { favoriteItemApi } from '../api'
import type { FavoriteItem, FavoriteItemQuery, FavoriteType } from '../types'
import CollectCard from '../components/CollectCard.vue'

// 路由
const route = useRoute()
const router = useRouter()

// 数据状态
const loading = ref(false)
const favoriteItems = ref<FavoriteItem[]>([])
const total = ref(0)

// 筛选条件
const selectedType = ref('')
const selectedFavoriteStatus = ref<boolean | undefined>(undefined)
const searchKeyword = ref('')

// 视图模式
const viewMode = ref<'grid' | 'waterfall'>('grid')

// 计算属性
const favoriteCount = computed(() => {
  return favoriteItems.value.filter(item => item.isFavorite).length
})

// 搜索防抖
let searchTimer: NodeJS.Timeout
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    loadFavoriteItems()
  }, 500)
}

// 加载收藏项
const loadFavoriteItems = async () => {
  loading.value = true
  try {
    // 从路由获取分类ID
    const categoryId = route.query.categoryId as string | undefined

    const params: FavoriteItemQuery = {
      categoryId: categoryId || undefined,
      type: (selectedType.value as FavoriteType) || undefined,
      keyword: searchKeyword.value || undefined,
      isFavorite: selectedFavoriteStatus.value
    }

    // 获取所有数据
    let items = await favoriteItemApi.getList(params)

    // 如果是未分类（categoryId === '-1'），需要过滤出没有categoryId的项
    if (categoryId === '-1') {
      items = items.filter(item => !item.categoryId)
    }

    favoriteItems.value = items
    total.value = items.length
  } catch (error) {
    ElMessage.error('加载收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 处理新增收藏
const handleCreateItem = () => {
  // 获取当前选中的分类ID
  const categoryId = route.query.categoryId as string | undefined

  // 如果选中了有效的分类（不是全部和未分类），则传递给创建页面
  if (categoryId && categoryId !== '-1') {
    router.push({
      path: '/collect/create',
      query: { categoryId }
    })
  } else {
    router.push('/collect/create')
  }
}

// 处理查看详情
const handleViewItem = (item: FavoriteItem) => {
  router.push(`/collect/detail/${item.id}`)
}

// 处理编辑
const handleEditItem = (item: FavoriteItem) => {
  router.push(`/collect/edit/${item.id}`)
}

// 处理删除
const handleDeleteItem = async (item: FavoriteItem) => {
  try {
    await ElMessageBox.confirm('确定要删除这个收藏吗？', '删除确认', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消'
    })

    await favoriteItemApi.delete(item.id)
    ElMessage.success('删除成功')
    await loadFavoriteItems()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理切换收藏状态
const handleToggleFavorite = async (item: FavoriteItem) => {
  try {
    await favoriteItemApi.toggleFavorite(item.id)
    item.isFavorite = !item.isFavorite
    ElMessage.success(item.isFavorite ? '已收藏' : '已取消收藏')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 监听筛选条件变化
watch([selectedType, selectedFavoriteStatus], () => {
  loadFavoriteItems()
})

// 监听路由query变化（分类选择）
watch(() => route.query.categoryId, () => {
  loadFavoriteItems()
})

// 初始化
onMounted(() => {
  loadFavoriteItems()
})
</script>

<style scoped>
/* 主内容区域样式 */
.collect-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.toolbar {
  padding: 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stats {
  display: flex;
  gap: 8px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
}

.favorites-main {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.favorites-waterfall {
  column-count: 4;
  column-gap: 16px;
  margin-bottom: 24px;
}

.favorites-waterfall > * {
  break-inside: avoid;
  margin-bottom: 16px;
}

/* 深色模式适配 */
.dark .collect-content {
  background: #1D1D1D;
}

.dark .toolbar {
  background: #252525;
  border-bottom-color: #3a3a3a;
}

/* 响应式瀑布流 */
@media (max-width: 1200px) {
  .favorites-waterfall {
    column-count: 3;
  }
}

@media (max-width: 900px) {
  .favorites-waterfall {
    column-count: 2;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .favorites-grid {
    grid-template-columns: 1fr;
  }

  .favorites-waterfall {
    column-count: 1;
  }

  .toolbar-left {
    flex-direction: column;
    align-items: stretch;
  }

  .search-bar {
    flex-direction: column;
    gap: 12px;
  }

  .search-bar > * {
    width: 100% !important;
  }
}
</style>
